package com.woohua.thread.lockscene;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/***
 * @title ReadWriteLockCache
 * @description
 * @author woo hua
 * @version 1.0.0
 * @create 2023/3/21 13:26
 **/
public class ReadWriteLockCache {

    final Map<Integer, Integer> map = new HashMap<>();
    private AtomicInteger totalReadTimes = new AtomicInteger();
    private AtomicInteger totalWriteTimes = new AtomicInteger();
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    Lock readLock = readWriteLock.readLock();
    Lock writeLock = readWriteLock.writeLock();

    public void put(Integer key, Integer val) {
        try {
            writeLock.lock();  // 写锁
            ReadWriteLockDemo.sleep(5); // 模拟写耗时
            totalWriteTimes.getAndIncrement();
            map.put(key, val);
        }finally {
            writeLock.unlock(); // 必须在finally 块解锁
        }
    }

    public Integer get(Integer key) {
        try {
            readLock.lock();    // 读锁
            totalReadTimes.getAndIncrement();
            return map.get(key);
        }finally {
            readLock.unlock();  // 必须在finally块释放锁
        }
    }

    public void printTime() {
        System.out.println("Read times: " + totalReadTimes.get() + ", Write times: " + totalWriteTimes.get());
    }
}
